(function(module){
	$.module.page.initView('roleList');
	var menuId=$.parseHrefParam('menuId');
	module[menuId]={
		tableCols: [function(){
			var cols=[//列表标题
				{ field: 'key', title: '角色编码'},
				{ field: 'name', title: '角色名称'},
				{ field: 'createUserName', title: '所有者'},
				{ field: 'changeTime', title: '更新时间'},
				{ title: '状态', width:85, templet: '#roleListStatusToolbar'},
				{ fixed: 'right', title:'操作', width: 200, minWidth: 200, toolbar: '#roleListRowToolbar'}
			];
			var local = layui.data('roleListTable'); // 获取对应的本地记录
			layui.each(cols, function(index, item) {
				if (item.field in local) {
					item.hide = local[item.field];
				}
			});
			return cols;
		}()],
		search: function(){
			module[menuId].selectRow=null;
			var search=$.formToData('roleListSearchForm');
			$.table.render({
				elem: '#roleListTable',
				toolbar: '#roleListToolbar',
				defaultToolbar: ['filter', {title: '导出',layEvent: 'auto-export',icon: 'layui-icon-export'}, 'print'],
				url: '/system/systemRole/findPageList', // 此处为静态模拟数据，实际使用时需换成真实接口
				method: 'post',
				contentType: 'application/json',
				request: {
					pageName: 'currPage',
					limitName: 'pageSize'
				},
				parseData: function(res) { // res 即为原始返回的数据
					return {
						"code": res.code, // 解析接口状态
						"msg": res.message, // 解析提示文本
						"count": res.body.totalSize, // 解析数据长度
						"data": res.body.dataList // 解析数据列表
					};
				},
				where: search,
				cols: module[menuId].tableCols,
				page: true,
				limit: 15,
				limits: [10, 15, 30, 50, 100, 200, 500, 1000],
				height: 'full-162',
				done: function(){
					$.auth.init($("#roleList"));
					module[menuId].loadEvent(this);
				}
			});
		},
		reload: function(){
			$.table.reload("roleListTable", {}, true);
		},
		loadEvent: function(that){
			$.table.on('row(roleListTable)', function(obj) {
				var data = obj.data; // 获取当前行数据
				obj.setRowChecked({
					type: 'radio' // radio 单选模式；checkbox 复选模式
				});
				module[menuId].selectRow=data;
				$("#roleList .layui-table-tool .layui-btn").each(function(){
					var button=$(this);
					if(button.hasClass('layui-btn-disabled')){
						button.removeClass('layui-btn-disabled');
					}
				});
			});
			$.table.on('toolbar(roleListTable)',function(obj){
				if(obj.event === 'add'){//增加
					module[menuId].add();
				}else if(obj.event === 'edit'){//编辑
					if(!module[menuId].selectRow){
						$.error("未选定行");
						return false;
					}
					if(module[menuId].selectRow.isAdmin){
						$.error("系统角色不能进行编辑操作");
						return false;
					}
					module[menuId].edit(module[menuId].selectRow.id);
				}else if(obj.event === 'authorize'){//授权
					if(!module[menuId].selectRow){
						$.error("未选定行");
						return false;
					}
					if(module[menuId].selectRow.isAdmin){
						$.error("系统角色不能进行授权操作");
						return false;
					}
					module[menuId].authorize(module[menuId].selectRow.id);
				}else if(obj.event === 'delete'){
					if(!module[menuId].selectRow){
						$.error("未选定行");
						return false;
					}
					if(module[menuId].selectRow.isAdmin){
						$.error("系统角色不能进行删除操作");
						return false;
					}
					module[menuId].delete(module[menuId].selectRow.id);
				}else if(obj.event === 'auto-export'){
					module[menuId].export();
				}else if(obj.event === 'lookLogger'){
					if(!module[menuId].selectRow){
						$.error("未选定行");
						return false;
					}
					module[menuId].lookLogger(module[menuId].selectRow.id);
				}
			});
			$.table.on('tool(roleListTable)', function(obj){
				var data = obj.data; // 获得当前行数据
			    if(obj.event === 'edit'){
					module[menuId].edit(data.id);
				}else if(obj.event === 'authorize'){
					module[menuId].authorize(data.id);
				}else if(obj.event === 'delete'){
					module[menuId].delete(data.id);
				}
			});
			$.form.on('switch(roleStatus)', function(obj) {
				module[menuId].status(obj.value, obj.elem.checked);
			});
			that.elem.next().on('mousedown', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]+', function() {
				var input = $(this).prev()[0];
				layui.data('roleListTable', {
					key: input.name,
					value: input.checked
				});
			});
		},
		export: function(){
			$.module.export.handle('角色导出', '/imexport/systemRole/export', $.formToData('roleListSearchForm'), '/imexport/systemRole/export/stop');
		},
		add: function(){
			$.get('/pages/admin/system/role/roleView.html', function(html){
				$.layer.open({
					title: '新建角色',
					type: 1,
					area: ['500px', '250px'],
					shade: 0.6, // 遮罩透明度
					shadeClose: true, // 点击遮罩区域，关闭弹层
					content: html,
					btn: ["确定", "取消"],
					yes: module[menuId].create
				});
			});
		},
		formRules: {
			key: [{ required: true, message: "角色编码不能为空"},{ regexp: /[0-9a-zA-Z]+/, message: "角色编码只能输入字母和数字"}],
			name: [{ required: true, message: "角色名称不能为空"}]
		},
		create: function(layerId){
			if(!$.valiForm('roleViewForm', module.currModule.formRules)){
				return false;
			}
			var data=$.formToData('roleViewForm');
			$.post('/system/systemRole/create', data, function(res){
				$.success("操作成功");
				module[menuId].reload();
				$.layer.close(layerId);
			}, 'json');
		},
		edit: function(id){
			$.get('/pages/admin/system/role/roleView.html', function(html){
				$.layer.open({
					title: '编辑角色',
					type: 1,
					area: ['500px', '250px'],
					shade: 0.6, // 遮罩透明度
					shadeClose: true, // 点击遮罩区域，关闭弹层
					content: html,
					btn: ["确定", "取消"],
					yes: module[menuId].update,
					success: function(){
						$.loadFormAjax('#roleViewForm', 'POST', '/system/systemRole/view', $.toJson({id: id}), function(){
							$("#roleViewForm [update='disabled']").attr("disabled",true);
						});
					}
				});
			});
		},
		update: function(layerId){
			if(!$.valiForm('roleViewForm', module.currModule.formRules)){
				return false;
			}
			var data=$.formToData('roleViewForm');
			$.post('/system/systemRole/update', data, function(res){
				$.success("操作成功");
				module[menuId].reload();
				$.layer.close(layerId);
			}, 'json');
		},
		authorize: function(id){
			module[menuId].selectId=id;
			$.get('/pages/admin/system/role/roleAuthorize.html', function(html){
				module[menuId].paramCache={};
				$.layer.open({
					title: '角色授权',
					type: 1,
					area: ['80%', '90%'],
					shade: 0.6, // 遮罩透明度
					shadeClose: true, // 点击遮罩区域，关闭弹层
					content: html,
					btn: ["确定", "取消"],
					yes: module[menuId].authorized,
					success: function(){
						$.tree.initView('role-authorize-tree-view', true);
						module[menuId].loadAuthorizeTree(id);
					}
				});
			});
		},
		loadAuthorizeTree: function(id){
			var search={roleId: id};
			$.post('/system/systemRole/findAuthorizeTree', search, function(data){
				data.checkbox=true;//展示复选框
				$.tree.loadTree('role-authorize-tree', data, function(node){
					module[menuId].currAauthorizeNode=node;
					var resourceId=node.data.id;
					module[menuId].authorizeView(id, resourceId);
				});
			}, 'json');
		},
		treeSearch: function(search, event){
			if(event.keyCode==13){
				$.warn("尚未实现");
			}
		},
		authorizeView: function(roleId, resourceId){
			$.get('/pages/admin/system/role/roleAuthorizeView.html',function(html){
				$("#role-authorize-tree-body").html(html);
				$.loadFormAjax('#roleAuthorizeViewForm', 'POST', '/system/systemRole/findAuthorizeView', $.toJson({roleId: roleId, resourceId: resourceId}), function(data, form){
					if(data.type=='menu' || data.type=='auth'){
						var inputTableList=$("#roleAuthorizeViewForm [lay-filter='inputTableList']");
						if(data.inputList && data.inputList.length>0){
							if(data.openInput){
								inputTableList.show();
							}
							for(var i=0, length=data.inputList.length; i<length; i++){
								module[menuId].addInputRow(data.inputList[i]);
							}
						}
						var outputTableList=$("#roleAuthorizeViewForm [lay-filter='outputTableList']");
						if(data.outputList && data.outputList.length>0){
							if(data.openOutput){
								outputTableList.show();
							}
							for(var i=0, length=data.outputList.length; i<length; i++){
								module[menuId].addOutputRow(data.outputList[i]);
							}
						}
						$.form.on('checkbox(input-all)', module[menuId].selectInputAll);
						$.form.on('checkbox(output-all)', module[menuId].selectOutputAll);
						$.form.on('switch(roleResourceSwitchOpenInput)', function(data) {
							this.value=this.checked+'';
							if(this.checked){
								inputTableList.show();
							}else{
								inputTableList.hide();
							}
						});
						$.form.on('switch(roleResourceSwitchOpenOutput)', function(data) {
							this.value=this.checked+'';
							if(this.checked){
								outputTableList.show();
							}else{
								outputTableList.hide();
							}
						});
					}
					$.form.render(null, 'roleAuthorizeViewForm');
				});
			});
		},
		selectInputAll: function(obj){
			var checked=obj.elem.checked;
			var selectRows=$("#roleAuthorizeViewForm [lay-filter='inputTableList'] tbody tr:visible [list-name='selectRow']");
			selectRows.each(function(){
				this.checked=checked;
			});
			$.form.render("checkbox", 'roleAuthorizeViewForm');
		},
		selectOutputAll: function(obj){
			var checked=obj.elem.checked;
			var selectRows=$("#roleAuthorizeViewForm [lay-filter='outputTableList'] tbody tr:visible [list-name='selectRow']");
			selectRows.each(function(){
				this.checked=checked;
			});
			$.form.render("checkbox", 'roleAuthorizeViewForm');
		},
		addInputRow: function(rowData){
			var rowModel=$("#roleAuthorizeViewForm [lay-filter='inputTableList'] [lay-filter='inputRowModel']");
			var tbody=rowModel.parent();
			var row=rowModel.clone(true);
			row.show();
			row.removeAttr("lay-filter");
			var checkbox=row.children(":eq(0)").find("input");
			checkbox.attr("dataid", rowData.id).attr("dataname",rowData.paramComment);
			if(rowData.checked){
				checkbox.attr("checked", true);
			}
			row.children(":eq(1)").html(rowData.paramComment);
			tbody.append(row);
		},
		addOutputRow: function(rowData){
			var rowModel=$("#roleAuthorizeViewForm [lay-filter='outputTableList'] [lay-filter='outputRowModel']");
			var tbody=rowModel.parent();
			var row=rowModel.clone(true);
			row.show();
			row.removeAttr("lay-filter");
			var checkbox=row.children(":eq(0)").find("input");
			checkbox.attr("dataid", rowData.id).attr("dataname",rowData.fieldComment);
			if(rowData.checked){
				checkbox.attr("checked", true);
			}
			row.children(":eq(1)").html(rowData.fieldComment);
			tbody.append(row);
		},
		setRoleAuthorize: function(tips){
			var data=$.formToData('roleAuthorizeViewForm');
			if(data.openInput){
				var selectRows=$("#roleAuthorizeViewForm [lay-filter='inputTableList'] tbody tr:visible [list-name='selectRow']");
				var inputList=[];
				selectRows.each(function(){
					if(this.checked){
						inputList.push({inputId: $(this).attr("dataid"), inputName: $(this).attr("dataname")});
					}
				});
				data.inputList=inputList;
			}
			if(data.openOutput){
				var selectRows=$("#roleAuthorizeViewForm [lay-filter='outputTableList'] tbody tr:visible [list-name='selectRow']");
				var outputList=[];
				selectRows.each(function(){
					if(this.checked){
						outputList.push({outputId: $(this).attr("dataid"), outputName: $(this).attr("dataname")});
					}
				});
				data.outputList=outputList;
			}
			if(data.id){
				module[menuId].paramCache[data.id]=data;
				if(tips!==false){
					$.success("设置成功");
				}
			}
		},
		authorized: function(layerId){
			module[menuId].setRoleAuthorize(false);
			var nodeList=$.tree.getCheckedList('role-authorize-tree');
			var list=[], resource, param;
			$(nodeList).each(function(index, item){
				resource={resourceId: item.id, resourceName: item.title};
				resource.resetParam=false;
				resource.openInput=false;
				resource.openOutput=false;
				param=module[menuId].paramCache[item];
				if(param){
					resource.resetParam=true;
					if(param.openInput){
						resource.openInput=param.openInput;
						resource.inputList=param.inputList;
					}
					if(param.openOutput){
						resource.openOutput=param.openOutput;
						resource.outputList=param.outputList;
					}
				}
				resource.openInputName=resource.openInput?'开启':'关闭';
				resource.openOutputName=resource.openOutput?'开启':'关闭';
				list.push(resource);
			});
			$.post('/system/systemRole/updateAuthorize', {roleId: module[menuId].selectId, list: list}, function(data){
				$.success("操作成功");
				module[menuId].selectId=undefined;
				module[menuId].paramCache={};
				module[menuId].reload();
				$.layer.close(layerId);
			}, 'json');
		},
		delete: function(id){
			$.layer.confirm("确定要删除此数据吗？", {btn:['确定','取消']}, function(){
				$.post('/system/systemRole/delete', {id: id}, function(data){
					$.success("操作成功");
					module[menuId].reload();
				}, 'json');
			}, function(){
				
			});
		},
		status: function(id, status){
			$.post('/system/systemRole/update',{id: id, status: status?1:0}, function(data){
				$.success("操作成功");
				module[menuId].reload();
			},'json');
		},
		clear: function(){
			$("#roleListSearchForm [name='name']").val('');
		},
		lookLogger: function(id){
			$.module.logger.look('systemRole', id);
		}
	};
	$.module.currModule=$.module[menuId];
	module[menuId].search();
})($.module);